package com.zim.aliot.service.impl;

import java.util.Base64;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.iot.model.v20180120.PubRequest;
import com.aliyuncs.iot.model.v20180120.PubResponse;
import com.zim.aliot.config.AliIotConfig;
import com.zim.aliot.service.AliClientService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AliClientServiceImpl implements AliClientService {

    @Autowired 
    private DefaultAcsClient defaultAcsClient;
    
    @Autowired
    private AliIotConfig aliIotConfig;
    
    private final Base64.Encoder encoder = Base64.getEncoder();
    
    @Override
    public boolean pubMessage(byte[] message, String deviceName) {
        
        PubRequest request = new PubRequest();
        request.setProductKey(aliIotConfig.getProductKey());
        request.setMessageContent(encoder.encodeToString(message));
        request.setTopicFullName("/" + aliIotConfig.getProductKey() + "/" + deviceName + "/get");

        request.setQos(0); //目前支持QoS0和QoS1
        try {
            PubResponse response = defaultAcsClient.getAcsResponse(request);
            if (response != null && response.getSuccess() != false) {
                return true;
            }else {
                log.error("【下发指令】:{}:{}",response.getRequestId(),response.getErrorMessage());
                return false;
            }
        } catch (ServerException e) {
            log.error("【下发指令】:{}",e.getMessage());
        } catch (ClientException e) {
            log.error("【下发指令】:{}",e.getMessage());
        }
        return false;
    }

    @Override
    public String registDevice(String deviceName) {
        // TODO Auto-generated method stub
        return null;
    }


}
